package com.pro.common.modules.service.dependencies.commondata.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.pro.common.modules.service.dependencies.model.response.CaptchaResponse;
import com.pro.framework.api.enums.EnumEnv;
import com.pro.common.api.model.ILoginInfo;
import com.pro.common.api.service.ITestService;
import com.pro.common.modules.service.dependencies.commondata.service.DevTranslateService;
import com.pro.common.modules.service.dependencies.upload.FileUploadService;
import com.pro.common.service.util.I18nUtils;
import com.pro.common.service.properties.BaseProperties;
import com.pro.framework.api.IReloadService;
import com.pro.framework.api.clazz.ClassCaches;
import com.pro.framework.api.enums.IEnumsService;
import com.pro.framework.api.util.AssertUtil;
import com.pro.framework.cache.CacheManagerCenterRedis;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.pro.common.api.CommonConst.Str.SYSTEM_CAPTCHA;

@Tag(name = "其他开放接口")
@RestController
@RequestMapping("/")
@Slf4j
public class CommonOtherController {

    @Autowired
    private List<IReloadService> reloadServices;/**/
    @Autowired
    private IEnumsService enumsService;
    @Autowired(required = false)
    private Map<String, ITestService> testServiceMap;
    @Autowired
    private DevTranslateService devTranslateService;
    @Autowired
    private BaseProperties baseProperties;
    @Autowired
    private CacheManagerCenterRedis cacheManagerCenterRedis;


    @GetMapping("/")
    @Operation(hidden = true)
    public void handle() {
    }

    @GetMapping("/favicon.ico")
    @Operation(hidden = true)
    public void handleFavicon() {

    }

    @Operation(summary = "重载站点所有可重载信息")
    @GetMapping("/common/reload")
    public void reload() {
        ClassCaches.clear();
        reloadServices.stream().sorted(Comparator.comparing(IReloadService::getSort)).forEach(IReloadService::reload);
    }

    @Operation(summary = "文件上传")
    @PostMapping("/common/file/upload")
    public List<String> upload(
            @Parameter(hidden = true) ILoginInfo loginInfo,
            @RequestParam(name = "file") MultipartFile[] files,
            @RequestParam(name = "module", required = false) String module,
            @RequestParam(name = "subModule", required = false) String subModule,
            @RequestParam(name = "oriNameFlag", required = false) Boolean oriNameFlag
    ) {
        return Arrays.stream(files).map(f -> FileUploadService.INSTANCE.uploadFile(loginInfo.getSysRole(), f, module, subModule, oriNameFlag)).collect(Collectors.toList());
    }

    @Operation(summary = "执行测试方法(仅非生产环境可用)")
    @GetMapping("/common/test")
    public void test() {
        if (testServiceMap != null) {
            testServiceMap.values().forEach(service -> {
                log.warn("test {} ", service.getClass());
                service.test();
            });
        }
    }

    @Operation(summary = "执行测试方法(仅非生产环境可用)")
    @GetMapping("/common/test/{serviceClassName}")
    public void test(@PathVariable String serviceClassName) {
        if (testServiceMap != null) {
            testServiceMap.entrySet().stream().filter(e -> e.getKey().toUpperCase().contains(serviceClassName.toUpperCase())).forEach(e -> {
                ITestService service = e.getValue();
                log.warn("test {} ", service.getClass());
                service.test();
            });
        }
    }

    @Operation(summary = "获取枚举字典列表", description = "包括当前语言的翻译单词")
    @GetMapping("/common/dictEnumFull/{simpleClassNames}")
    public Map<String, List<Map<String, Object>>> dictEnumFull(@PathVariable("simpleClassNames") String simpleClassNames) {
//        boolean isAdmin = EnumApplication.admin.equals(commonProperties.getApplication());
//        boolean isAdminChinese = isAdmin && EnumAuthDict.ADMIN_LANG_CHINESE.getValueCacheOrDefault(true);
        // 翻译label
        return Arrays.stream(simpleClassNames.split(",")).collect(Collectors.toMap(c -> c,
                simpleClassName -> {
                    //noinspection rawtypes
                    Class<? extends Enum> eClass = enumsService.getEnumClass(simpleClassName);
                    AssertUtil.notEmpty(eClass, "_类不存在", simpleClassName);
                    List<Map<String, Object>> fullList = enumsService.getFullList(eClass);
                    // 翻译label
                    fullList.forEach(e -> e.put("label", StrUtil.blankToDefault(I18nUtils.get((String) e.get("label")), (String) e.get("code"))));
                    return fullList;
                }));
    }

    @Operation(summary = "获取枚举字典列表", description = "包括当前语言的翻译单词")
    @GetMapping("/common/dictEnumSimple/{simpleClassNames}")
    public Map<String, List<Map<String, Object>>> dictEnumSimple(@PathVariable("simpleClassNames") String simpleClassNames) {
        // 翻译label
        return Arrays.stream(simpleClassNames.split(",")).distinct().collect(Collectors.toMap(c -> c,
                simpleClassName -> {
                    //noinspection rawtypes
                    Class<? extends Enum> eClass = enumsService.getEnumClass(simpleClassName);
                    AssertUtil.notEmpty(eClass, "_类不存在", simpleClassName);
                    List<Map<String, Object>> fullList = enumsService.getSimpleList(eClass);
                    // 翻译label
                    fullList.forEach(e -> e.put("label", StrUtil.blankToDefault(I18nUtils.get((String) e.get("label")), (String) e.get("code"))));
                    return fullList;
                }));
    }

    @Operation(summary = "开发接口增量加载翻译", description = "实体类名,属性名,基础站点文案单词,存入到messages_zh_CN.properties")
    @GetMapping(value = "/dev/reloadTranslateKeys")
    public String reloadTranslateKeys(@Parameter(hidden = true) ILoginInfo loginInfo) {
        AssertUtil.isTrue(EnumEnv.dev.equals(baseProperties.getCommonEnv()), "只有本地启动执行才有意义");
        return devTranslateService.reloadTranslateKeys();
    }
    @Operation(summary = "用户端请求图形验证码")
    @PostMapping("/common/getCaptcha")
    public CaptchaResponse generate() throws IOException {
        // 生成线干扰验证码，4位数字
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        captcha.setGenerator(new RandomGenerator("0123456789", 4));
        String captchaCode = captcha.getCode();

        // 存 Redis
        String captchaKey = UUID.randomUUID().toString();
        cacheManagerCenterRedis.put(
                SYSTEM_CAPTCHA,
                captchaKey,
                captchaCode,
                5L, TimeUnit.MINUTES
        );
        // 转 Base64
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        captcha.write(out);
        String base64Img = Base64.getEncoder().encodeToString(out.toByteArray());

        CaptchaResponse result = new CaptchaResponse();
        result.setCaptchaKey(captchaKey);
        result.setCaptchaImage(base64Img);
        return result;
    }

//    @Operation(summary = "发送短信")
//    @PostMapping("/sendCode")
//    public R<?> sendCode(@Parameter(hidden = true) ILoginInfo loginInfo, @RequestBody UserSendMsgRequest request) {
//        UserMsg userMsg = new UserMsg();
//        BeanUtils.copyPropertiesModel(loginInfo, userMsg);
//
//        SysMsgRecord sysMsgRecord = request.getSysMsgRecord();
//        String code = RandomUtil.randomNumbers(6);
//
//        String key = sysMsgService.getMsgKey(userMsg, sysMsgRecord.getBusinessCode());
//
//        cacheManagerCenter.put(CommonConst.CacheKey.SmsCode, key, code, 10, TimeUnit.MINUTES);
//        sysMsgRecord.setParamMap(Collections.singletonMap("code", code));
//
//        userMsg.setLang(LocaleContextHolder.getLocale().toLanguageTag());
//        List<SysMsgRecord> sysMsgRecords = sysMsgService.send(userMsg, sysMsgRecord);
//        if (sysMsgRecords.isEmpty()) {
//            throw new BusinessException("消息未发送_请检查消息配置");
//        }
//        return R.ok();
//    }


//    @Operation(summary = "用户端获取图形验证码")
//    @PostMapping("getCaptcha")
//    @SneakyThrows
//    public void generate(HttpServletRequest request, HttpServletResponse response) {
//        // 定义图形验证码的长、宽、验证码字符数、干扰线宽度 createCircleCaptcha
////        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
//        // 纯数字验证码（基于hutool工具类封装）
//        NumberCaptcha captcha = new NumberCaptcha(200, 100, 4);
//        // 将验证码存入session缓存
//        request.getSession().setAttribute(CommonConst.Str.SYSTEM_CAPTCHA, captcha.getCode());
//        ServletOutputStream outputStream = response.getOutputStream();
//        captcha.write(outputStream);
//        outputStream.flush();
//    }


//    // "/loginUserIds"
//    @Operation(summary = "查询当前在线用户id列表")
//    @GetMapping(CommonConst.Str.path_loginUserIds)
//    public R<String> loginUserIds() {
//        Map<Long, ILoginInfo> map = MyWebSocketHandlerDecoratorFactory.loginUserMap;
//        return R.ok(map.values().stream().map(o -> o.getId().toString()).collect(Collectors.joining(",")));
//    }

//    /**
//     * 用户端 显示当地语言
//     * 后台   优先显示中文
//     */
//    private static String doTranslate(boolean isAdmin, Boolean isAdminChinese, String labelChinese, String code) {
//        if (labelChinese == null) {
//            return null;
//        }
//        String labelTranslate = I18nUtils.get(labelChinese);
//        // 后台
//        if (isAdmin) {
//            if (isAdminChinese) {
//                return labelChinese;
//            } else {
//                return LogicUtils.or(labelTranslate, labelChinese);
//            }
//        } else {
//            // 用户端
//            return StrUtil.blankToDefault(I18nUtils.get(labelChinese), code);
//        }
//    }
}
